<template>
  <ele-page flex-table :multi-card="false" hide-footer style="min-height: 420px">
    <ele-card flex-table :body-style="{ padding: '0 0 0 16px', overflow: 'hidden' }">
      <ele-split-panel
        ref="splitRef"
        flex-table
        size="180px"
        allow-collapse
        :custom-style="{ borderWidth: '0 1px 0 0', padding: '16px 0' }"
        :body-style="{ padding: '16px 16px 0 0', overflow: 'hidden' }"
        :style="{ height: '100%', overflow: 'visible' }"
      >
        <el-tree :data="treeData" :props="defaultProps" />

        <template #body>
          <record-search :where="defaultWhere" @search="reload" />

          <ele-pro-table
            ref="tableRef"
            row-key="id"
            :columns="columns"
            :datasource="datasource"
            :show-overflow-tooltip="true"
            :highlight-current-row="true"
            :export-config="{ fileName: '登录日志数据' }"
            :where="defaultWhere"
            cache-key="systemLoginRecordTable"
            :footer-style="{ paddingBottom: '16px' }"
          >
            <template #toolbar>
              <el-button type="primary" class="ele-btn-icon" @click="exportData">
                新建
              </el-button>
              <el-button type="danger" class="ele-btn-icon" @click="exportData">
                删除
              </el-button>
            </template>

            <template #action="{ row }">
              <el-link type="primary" :underline="false" @click="openEdit(row)">
                修改
              </el-link>
              <el-divider direction="vertical" />
              <ele-dropdown
                :items="[
                  { title: '转正', command: 'password' },
                  { title: '删除', command: 'delete', danger: true, divided: true },
                ]"
                style="display: inline"
                @command="(key) => dropClick(key, row)"
              >
                <el-link type="primary" :underline="false">
                  <span>更多</span>
                  <el-icon :size="12" style="vertical-align: -1px; margin-left: 2px">
                    <ArrowDown />
                  </el-icon>
                </el-link>
              </ele-dropdown>
            </template>
          </ele-pro-table>
        </template>
      </ele-split-panel>
    </ele-card>
  </ele-page>
</template>

<script setup>
import { ref, reactive } from "vue";
import { EleMessage } from "ele-admin-plus/es";
import ExcelJS from "exceljs";
import { download } from "@/utils/common";
import { DownloadOutlined } from "@/components/icons";
import RecordSearch from "./components/record-search.vue";
import { pageLoginRecords, listLoginRecords } from "@/api/system/login-record";

defineOptions({ name: "SystemLoginRecord" });

/** 默认搜索条件 */
const defaultWhere = reactive({
  username: "",
  nickname: "",
});

const defaultProps = {
  children: "children",
  label: "label",
};
const treeData = [
  {
    label: "见证员",
  },
  {
    label: "取样员",
  },
];
/** 表格实例 */
const tableRef = ref(null);

/** 表格列配置 */
const columns = ref([
  {
    type: "selection",
    columnKey: "selection",
    width: 50,
    align: "center",
  },
  {
    type: "index",
    columnKey: "index",
    width: 50,
    align: "center",
  },
  { label: "人员编号", prop: "personId" },
  { label: "姓名", prop: "name" },
  { label: "单位名称", prop: "unitName" },
  { label: "身份证号", prop: "idNumber" },
  { label: "性别", prop: "gender" },
  { label: "证书编号", prop: "certificateNumber" },
  { label: "出生日期", prop: "birthDate" },
  { label: "年龄", prop: "age" },
  { label: "职务", prop: "position" },
  { label: "职称", prop: "title" },
  { label: "学历", prop: "education" },
  { label: "专业", prop: "major" },
  { label: "联系电话", prop: "contactPhone" },
  { label: "状态", prop: "status" },
  {
    columnKey: "action",
    label: "操作",
    width: 128,
    align: "center",
    slot: "action",
    hideInPrint: true,
    hideInExport: true,
    fixed: "right",
  },
]);

/** 表格数据源 */
const datasource = ({ pages, where, orders, filters }) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const records = Array.from({ length: 10 }, (_, index) => ({
        personId: `ID-${String(index + 1).padStart(4, "0")}`,
        name: `姓名${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${index}`,
        unitName: `单位${String.fromCharCode(65 + Math.floor(Math.random() * 26))}`,
        idNumber: `${Math.floor(10000000000 + Math.random() * 90000000000)}`,
        gender: ["男", "女"][Math.floor(Math.random() * 2)],
        certificateNumber: `证书-${String(index + 1).padStart(4, "0")}`,
        birthDate: new Date(
          new Date().getFullYear() - Math.floor(Math.random() * 60),
          Math.floor(Math.random() * 11),
          Math.floor(Math.random() * 28)
        )
          .toISOString()
          .split("T")[0],
        age: Math.floor(Math.random() * 60),
        position: ["经理", "主管", "员工"][Math.floor(Math.random() * 3)],
        title: ["初级", "中级", "高级"][Math.floor(Math.random() * 3)],
        education: ["初中", "高中", "本科", "硕士", "博士"][
          Math.floor(Math.random() * 5)
        ],
        major: ["计算机科学", "数学", "物理", "化学", "生物学"][
          Math.floor(Math.random() * 5)
        ],
        contactPhone: `1${Math.floor(100000000 + Math.random() * 900000000)}`,
        status: ["在职", "离职", "休假"][Math.floor(Math.random() * 3)],
      }));
      resolve({
        list: records,
        count: 100,
      });
    });
  });
};

/** 刷新表格 */
const reload = (where) => {
  tableRef.value?.reload?.({ page: 1, where });
};

/** 导出数据 */
const exportData = () => {
  // 请求查询全部接口
  const loading = EleMessage.loading({
    message: "请求中..",
    plain: true,
  });
  tableRef.value?.fetch?.(({ where, orders, filters }) => {
    listLoginRecords({ ...where, ...orders, ...filters })
      .then((data) => {
        const workbook = new ExcelJS.Workbook();
        const sheet = workbook.addWorksheet("Sheet1");
        sheet.addRow([
          "账号",
          "用户名",
          "IP地址",
          "设备型号",
          "操作系统",
          "浏览器",
          "操作类型",
          "备注",
          "登录时间",
        ]);
        data.forEach((d) => {
          sheet.addRow([
            d.username,
            d.nickname,
            d.ip,
            d.device,
            d.os,
            d.browser,
            ["登录成功", "登录失败", "退出登录", "刷新TOKEN"][d.loginType],
            d.comments,
            d.createTime,
          ]);
        });
        // 设置列宽
        [16, 16, 22, 22, 18, 20, 14, 16, 24].forEach((width, index) => {
          sheet.getColumn(index + 1).width = width;
        });
        // 设置样式
        sheet.eachRow({ includeEmpty: true }, (row, rowIndex) => {
          row.height = 20;
          row.eachCell({ includeEmpty: true }, (cell) => {
            cell.border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
            };
            cell.alignment = {
              vertical: "middle",
              horizontal: "center",
            };
            cell.font = { size: 12, bold: rowIndex === 1 };
          });
        });
        // 下载文件
        workbook.xlsx.writeBuffer().then((data) => {
          download(data, "登录日志.xlsx");
          loading.close();
        });
      })
      .catch((e) => {
        loading.close();
        EleMessage.error(e.message);
      });
  });
};
</script>
